
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);
function hengshuping() {
	if (window.orientation == 90 || window.orientation == -90) {
		alert("为了有更好的浏览体验，请保持竖屏观看！")
	}
}

var dataBase = {
	zoomLevel : 1,
};

// 获取数据
var getData = {
	areaList : function() {
		getData.seatList();
	},
	seatList : function(receiveData) {
		// var data = receiveData;
		// var seatListData = data.result;
		// console.log("传到seatList", data)
		// dataBase["seatMap"] = seatListData;
		// 渲染座位图
		renderData.seatMap();
		//renderData.priceList(seatListData.priceList)
		//renderData.querySalePrice(seatListData.querySaleclassList);
	}
}

// 渲染数据
var renderData = {
	seatMap : function(data) {
		dataBase["priceList"] = priceList;
		
		var formatMap = initMapData();
		console.log('=====最终seatMap=====');
		console.log(formatMap);
		dataBase["formatMap"] = formatMap;
		// 座位类型设置
		var priceGradeSeats = getPriceGradeSeats();
		// id所映射的座位数据
		var idMapSeat = dataBase["idMapSeat"];
		//console.log(idMapSeat);
		var $cart = $("#seat-info");
		var $counter = $(".count-seat");
		var $total = $(".count-money");
		
		var SeatMAP = $('#renderSeat').seatCharts({
			map: formatMap,
			naming : {
				top : false,
				getLabel : function (character, row, column) {
					return '';
				}
			},
			seats: priceGradeSeats,
			click: function () {
				if (this.status() == 'available') {
					//购买张数还没限制
					// var orderNeedInfo = dataBase.orderNeedInfo;
					// var ticketNumber = orderNeedInfo.restrictionNotice
					// 		- dataBase.showDiscount;
					// console.log("sessionStorage存储",
					// 		orderNeedInfo);
					// console.log("剩余可购买张数", ticketNumber);
					// if (orderNeedInfo.restrictionNotice != 0) {
					// 	if (SeatMAP.find('selected').length >= ticketNumber) {
					// 		alert("本场演出最多购买"
					// 				+ orderNeedInfo.restrictionNotice
					// 				+ "张,\n您已经购买过"
					// 				+ dataBase.showDiscount
					// 				+ "张,\n本次购买不得超过"
					// 				+ ticketNumber + "张！");
					// 		return "available";
					// 	}
					// }
					var oSeat = idMapSeat[this.settings.id];
					if (typeof(oSeat) == "undefined") {
						Wei.Util.wapTipNew({msg: '该座位尚未设置价格', icon: 2});
						return 'available';
					}
					
					var sSeat = oSeat.region_name + oSeat.site;
					$(
							'<li><input type="hidden" name="ids[]" value="'+oSeat.id+'" /><span class="seat '+oSeat.classes+'"></span><span>'
									+ sSeat
									+ '</span> <span class="delete"></span><span class="price">'
									+ oSeat.real_price
									+ '元</span></li>')
							.attr(
									{
										'id' : 'cart-item-' + this.settings.id,
										'priceId' : oSeat.pid,
										'price' : oSeat.real_price
									}).data('seatId',
									this.settings.id)
							.appendTo($cart);
					$counter.text(SeatMAP.find('selected').length + 1);
					$total.text(recalculateTotal(SeatMAP, "+", this.data().price));
					// interaction.packageRules();
					$(".checked-seat-info").css({
						visibility : 'visible'
					});
					interaction.judgeIsShowFooter();
					return 'selected';
				} else if (this.status() == 'selected') {
					// update the counter
					$counter.text(SeatMAP.find('selected').length - 1);
					// and total
					$total.text(recalculateTotal(SeatMAP, "-", this.data().price));
					// remove the item from our cart
					$('#cart-item-' + this.settings.id).remove();
					// interaction.packageRules();
					// seat has been vacated

					if ($("#moneyCount").text() == "0") {
						$(".checked-seat-info").css({
							visibility : 'hidden'
						})
					}
					interaction.judgeIsShowFooter();
					return 'available';
				} else if (this.status() == 'unavailable') {
					//seat has been already booked
					return 'unavailable';
				} else {
					return this.style();
				}
			}
		});

		// 设置对应的价格
		// for ( var t in priceGradeSeats) {
		// 	$("." + priceGradeSeats[t].classes).css({
		// 		color : priceGradeSeats[t].bgColor
		// 	})
		// }
		
		// 设置锁定的座位
		SeatMAP.get(dataBase["soldSeat"]).status('unavailable');

		// 点击删除按钮
		$cart.on('click', '.delete',
				function() {
					SeatMAP.get($(this).parents('li:first').data('seatId')).click();
				});
		
		// 设置座位容器宽度
		interaction.setSeatContainerWidth();
		drag('renderSeat');
		
		$(".seat-loading").hide();
		$('#renderSeat').each(function() {
			new RTP.PinchZoom($(this), {});
		});
		$('#renderSeat').trigger("resize");
		//interaction.isShowInitStage();

		function getPriceGradeSeats() {
			var priceGradeSeats = {};
			for (var i = 0; i < priceList.length; i++) {
				var item = priceList[i];
				priceGradeSeats[item.tag] = {
					price : item.price,
					classes : item.classes,
					category : item.category,
					//bgColor : price.ticketPriceColor,
				}
			}
			console.log(priceGradeSeats);
			return priceGradeSeats;
		}
		
		function initMapData() {
			//console.log('initMapData');
			// 存放售卖的座位;
			dataBase["soldSeat"] = [];
			dataBase["stage"] = [];
			// 存放ID 映射(对应)的座位数据
			dataBase["idMapSeat"] = {};
			
			//解析productSeatJson数据
			//console.log(productSeatJson.length)
			for (var i = 0; i < productSeatJson.length; i++) {
				var x = productSeatJson[i].x;
				var y = productSeatJson[i].y;
				// var priceGrade = interaction.getOnlyAppointObj(priceList,
				// 		"ticketPriceId", seatList[i].pid).priceGradeShow;
				// var flagArr = tempArr[y - mapSize.minY].split("");
				// flagArr[x - mapSize.minX] = priceGrade;
				// tempArr[y - mapSize.minY] = flagArr.join("");
				//var seatMapId = (y - mapSize.minY + 1) + "_" + (x - mapSize.minX + 1);
				var seatMapId = x + "_" + y;
				// 判断是否已售
				if (productSeatJson[i].status == 2 || productSeatJson[i].status == 3) {
					dataBase["soldSeat"].push(seatMapId);
				}
				if (productSeatJson[i].tag == 'z') { //不可选座位
					//console.log(seatMapId)
					dataBase["soldSeat"].push(seatMapId);
				}
				if (productSeatJson[i].pid == 0) {
					dataBase["stage"].push(seatMapId);
				}
				dataBase["idMapSeat"][seatMapId] = productSeatJson[i];
			}
			
			var tempArr = initSeatMap;
			return tempArr;
		}

		function recalculateTotal(SeatMAP, type, price) {
			var total = 0;
			// basically find every selected seat and sum its price
			SeatMAP.find('selected').each(function() {
				total += this.data().price;
			});
			console.log('total:'+total);
			console.log('price:'+price);
			if (type == "+") {
				return Math.round(total * 100 + price * 100) / 100;
			} else {
				return Math.round(total * 100 - price * 100) / 100;
			}
		}
	}
}

// 交互
var interaction = {
	// 设置座位容器宽度
	setSeatContainerWidth : function() {
		var mapMaxSeatCount = dataBase["formatMap"][0].length;
		var seatWidth = $(".seatCharts-cell").outerWidth(true);
		//console.log(seatWidth);
		$("#renderSeat").width(mapMaxSeatCount * seatWidth);
		//alert(window.innerWidth / (mapMaxSeatCount * seatWidth));
		var scale = window.innerWidth / (mapMaxSeatCount * seatWidth);
		//alert(scale);
		$('#renderSeat').css({
			transform : 'scale(' + scale + ')'
		})
	},
	// 提交座位
	commitSeat : function() {
		$("#commitSeat").click(
			function() {
				var btn = $(this),
					form = btn.parents('form.J_ajaxForm');
				
				var $checkedSeat = $(".selected").not(".seat-status");
				if ($checkedSeat.length <= 0) {
					alert("请选择一个座位再提交！")
					return;
				}
				var data = [];
				$checkedSeat.each(function(index, item) {
					var mapId = $(item).attr("id");
					var idMapSeat = dataBase['idMapSeat'][mapId];
					// var price = interaction.getOnlyAppointObj(
					// 		dataBase['priceList'], "ticketPriceId",
					// 		idMapSeat.pid).price;
					//var priceId = idMapSeat.pid;
					var seatId = idMapSeat.id;

					data.push({
						//"price" : price, // 票价
						//"priceId" : priceId, // 票价Id
						"seatId" : seatId, // 座位ID
						//"count" : "1", // 张数
						//"actuallyPrice" : price, // 实际票价
						//"freeTicketCount" : "1", // 套票数量
					})
				})

				//var orderNeedInfo = dataBase.orderNeedInfo;

				//var isRealName = orderNeedInfo.userregtype == "" ? "0" : orderNeedInfo.userregtype + "";

				//console.log({"orderNeedInfo" : orderNeedInfo})
				//console.log('isRealName', isRealName)
				
				var param = {
					"initMode": initMode,
					"initPid": pid,
					"initSpecId": specId,
					"data": data,
					"param": {
						// "theaterId" : orderNeedInfo.theaterId,
						// "projectId" : orderNeedInfo.projectId,
						// "projectName" : orderNeedInfo.productName,
						// "date" : new Date().getTime(),
						// "showId" : orderNeedInfo.showId,
						// "showTime" : orderNeedInfo.showTime,
						// "placeId" : orderNeedInfo.placeId,
						// "venueId" : orderNeedInfo.venueId,
						// "isRealName" : isRealName,
						// "manageWayCode" : orderNeedInfo.manageWayCode
					}
				}
				var index = layer.load(1, {
					shade: [0.1,'#fff'],
					time: 1000
				});
				//下面提交订单
				$.post(url_doBuyVerify, param, function(ret){
					if(ret.code == 1){
						//form.submit();
						var data = ret.data;
    					window.location.href = url_orderPrepair+'?initMode='+initMode+'&initPid='+pid+'&initSpecId='+specId+'&idStr='+data.idStr;
					}else if(ret.code == 0){
						Wei.Util.wapTipNew({msg: ret.msg, icon: 2, data: ret.data});
					}
				},'json');
			})
	},
	judgeIsShowFooter : function() {
		var seatLength = $("#seat-info").find("li").length;
		if (seatLength == 0) {
			$(".commit-seat").hide();
			$(".price-list").show();
		} else {
			$(".commit-seat").show();
			$(".price-list").hide();
		}
	},
	isShowInitStage: function(){
		if(dataBase.stage.length){
			console.log('自定义舞台')
			$('.choose-seat>.stage').hide();
		}
	}
}

getData.areaList();
interaction.commitSeat();
